﻿using Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebServiceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadPool.SetMaxThreads(1000, 1000);
            Request();
            Console.ReadKey();
        }

        static void Request()
        {
            ThreadPoolMessage("Start");
            //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:5700/Handler.ashx");
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.baidu.com");
            webRequest.Method = "post";

            IAsyncResult result = webRequest.BeginGetRequestStream(
                new AsyncCallback(EndGetRequestStream), webRequest);
        }

        static void EndGetRequestStream(IAsyncResult result)
        {
            ThreadPoolMessage("RequestStream Complete");

            HttpWebRequest webRequest = (HttpWebRequest)result.AsyncState;
            Stream stream = webRequest.EndGetRequestStream(result);

            byte[] condition = Encoding.Default.GetBytes("Id:1");
            stream.Write(condition, 0, condition.Length);

            IAsyncResult responseResult = webRequest.BeginGetResponse(
                new AsyncCallback(EndGetResponse), webRequest);
        }

        static void EndGetResponse(IAsyncResult result)
        {
            ThreadPoolMessage("GetResponse Complete");

            HttpWebRequest webRequest = (HttpWebRequest)result.AsyncState;
            WebResponse webResponse = webRequest.EndGetResponse(result);

            Stream stream = webResponse.GetResponseStream();
            //BinaryFormatter formatter = new BinaryFormatter();
            //var person = (Person)formatter.Deserialize(stream);
            //Console.WriteLine($"Person Id:{person.ID} name:{person.Name}, Age:{person.Age}");
        }

        //显示线程池现状
        static void ThreadPoolMessage(string data)
        {
            int a, b;
            ThreadPool.GetAvailableThreads(out a, out b);
            string message = string.Format("{0}\n  CurrentThreadId is {1}\n  " +
                  "WorkerThreads is:{2}  CompletionPortThreads is :{3}\n",
                  data, Thread.CurrentThread.ManagedThreadId, a.ToString(), b.ToString());

            Console.WriteLine(message);
        }
    }
}




namespace Model
{
    [Serializable]
    public class Person
    {
        public int ID
        {
            get;
            set;
        }
        public string Name
        {
            get;
            set;
        }
        public int Age
        {
            get;
            set;
        }
    }
}